<template>
    <div class="code-container">
      <button class="copy-button" @click="copyCode">复制代码</button>
      <pre v-if="code" class="code-block">
        <code ref="codeBlock" class="javascript">{{ code }}</code>
      </pre>
    </div>
  </template>
  
  <script setup lang="ts">
  import { ref, onMounted, defineProps } from 'vue';
  import hljs from 'highlight.js';
  import 'highlight.js/styles/atom-one-dark.css'; //代码高亮样式
  import { message } from "@/utils/message";
  const props = defineProps<{
    code: string;
  }>();
  
  const codeBlock = ref<HTMLElement | null>(null);
  onMounted(() => {
    if (codeBlock.value) {
      hljs.highlightElement(codeBlock.value);
    }
  });
  
  const copyCode = async () => {
    if (props.code) {
      try {
        await navigator.clipboard.writeText(props.code);
        message("复制成功", { type: "success" });
      } catch (err) {
        message("复制失败", { type: "error" });
      }
    }
  };
  
  </script>
  
  <style>
.code-container {
  position: relative;
  height: 100%; /* 让容器填满父元素 */
}

.code-block {
  background-color: #282c34;
  border-radius: 5px;
  white-space: pre;  /* 保留换行和空格 */
  word-wrap: break-word;  /* 在需要时断开长单词 */
  margin: 0; /* 清除默认 margin */
  max-height: calc(75vh - 100px); /* 设置最大高度 */
  overflow: auto;   /* 允许滚动条出现 */
}

/* 默认隐藏复制按钮 */
.copy-button {
  position: absolute;
  top: 10px;
  right: 10px;
  padding: 6px 12px;
  border: none;
  background-color: #409eff; /* Element Plus 的蓝色 */
  color: white;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s ease;
  opacity: 0; /* 初始透明度为 0，隐藏按钮 */
  pointer-events: none; /* 不占用鼠标事件 */
}

/* 当鼠标悬停在代码块上时显示复制按钮 */
.code-container:hover .copy-button {
  opacity: 1; /* 完全可见 */
  pointer-events: auto; /* 允许鼠标事件 */
}

.copy-button:hover {
  background-color: #66b1ff; /* 悬停状态颜色 */
}
</style>